import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:oi_ai_tool/model/archive.dart';
import 'package:oi_ai_tool/model/chat_message.dart';
import 'package:oi_ai_tool/services/chat_service.dart';
import 'package:oi_ai_tool/util/draw_util.dart';
import 'package:oi_ai_tool/util/oi_logger.dart';
import 'package:oi_ai_tool/util/storage.dart';
import 'package:oi_ai_tool/util/timeUtil.dart';
import 'package:oi_ai_tool/widgets/toast.dart';

class HomePageController extends GetxController {
  int tabIndex = 0;
  int floatIndex = 1;

  TextEditingController userTalkTextController = TextEditingController();
  ScrollController scrollController = ScrollController();

  FocusNode oifocusNode = FocusNode();
  bool floatButtonVisible = true;

  List<ChatMessage> _mockdata = <ChatMessage>[];
  List<Archive> chatArchive = <Archive>[];
  ChatService chatService = Get.find<ChatService>();
  RxString userTalk = "".obs;
  late Worker submitWorker;

  get mockdata {
    return _mockdata;
  }

  bool inputEnable = true;
  double mainHeight = 0;

  double viewinsetsBootm = 0;
  @override
  onReady() async {
    super.onReady();
    await refreshData();
    submitWorker = debounceSubmit();
  }

  Future refreshData() async {
    EasyLoading.show();
    var data = await OiStorage.get(StoreageKey.CHAT_LIST);
    var archiveData = await OiStorage.get(StoreageKey.ARCHIVE_LIST);
    if (data != null) {
      List<dynamic> list = jsonDecode(data);

      _mockdata = ChatMessage.formListJson(list);
    }
    if (archiveData != null) {
      chatArchive = Archive.fromListJson(json.decode(archiveData));
      OiLogger.info(msg: "$chatArchive");
    }
    EasyLoading.dismiss();
    update();
  }

  initFloatButton() {
    if (viewinsetsBootm > 30) {
      floatButtonVisible = false;
    } else {
      floatButtonVisible = true;
    }
  }

  onSelectTab(int i) {
    tabIndex = i;
    // OiLogger.debug(msg: "$i $tabIndex");
    update();
  }

  ontextFocus() {
    floatButtonVisible = !oifocusNode.hasFocus;
    // oifocusNode.dispose();
    oifocusNode.addListener(() {
      // OiLogger.debug(msg: "${oifocusNode.hasFocus}");
      floatButtonVisible = !oifocusNode.hasFocus;
      update();
    });
    // scrollBottom();
  }

  scrollBottom() {
    scrollController.animateTo(
        scrollController.position.maxScrollExtent.sp +
            ScreenUtil().bottomBarHeight,
        duration: const Duration(milliseconds: 1000),
        curve: Curves.easeInOut);
  }

  onSubmit() async {
    // String userTalk = .toString().trim();
    String userTalkStr = userTalkTextController.text;
    userTalk.value = userTalkStr;

    update();
  }

  Worker debounceSubmit() {
    return debounce<String>(userTalk, (userchatdata) {
      if (userchatdata.isNotEmpty && inputEnable) {
        inputEnable = false;
        // OiLogger.debug(msg: "userTalk");
        ChatMessage chat = ChatMessage(role: "user", content: userchatdata);

        mockdata.add(chat);
        saveChatData();
        ChatMessage anwser = ChatMessage(role: "assistant", content: "");

        chatService.chat(
            chatLsit: _mockdata,
            onMsg: (data) => onChatMsg(data: data, anwser: anwser));
        userTalkTextController.clear();
        scrollBottom();
        OiLogger.info(msg: "user:$chat");
      } else {
        OiToast.msg("考虑问我点什么？", gravity: ToastGravity.CENTER);
      }
      oifocusNode.unfocus();
      // refreshData();
      update();
    }, onDone: () {
      OiLogger.info(msg: "onDone");
    }, time: const Duration(milliseconds: 500));
  }

  void onChatMsg({required String data, required ChatMessage anwser}) {
    if (data.isNotEmpty) {
      var jsonData = data.replaceAll("data:", "");
      var dataMap = jsonDecode(jsonData);
      if (dataMap["sentence_id"] == 0) {
        mockdata.add(anwser);
      }
      anwser.content = anwser.content + dataMap['result'];
      scrollBottom();
      if (dataMap['is_end']) {
        saveChatData();
        // scrollBottom();
        inputEnable = true;
      }
      // OiLogger.info(msg: anwser.content);

      update();
    }
  }

  void saveChatData() {
    OiStorage.set(
        StoreageKey.CHAT_LIST, jsonEncode(ChatMessage.toListJson(mockdata)));
  }

  void archive() async {
    if (_mockdata.isNotEmpty) {
      chatArchive.add(
          Archive(chatList: _mockdata, archiveTime: TimeUtils.getTimeStamp()));
      await saveArchive();
      await delChatList();
      _mockdata = [];
      OiToast.msg("归档成功！");
      refreshData();
    } else {
      OiToast.warning("当前对话为空，无法归档！");
    }
  }

  Future<bool> delChatList() async =>
      await OiStorage.remove(StoreageKey.CHAT_LIST);

  archivetoChat(BuildContext context, int? index) {
    Archive archive = chatArchive[index!];
    _mockdata = archive.chatList;
    OiStorage.set(StoreageKey.CHAT_LIST, jsonEncode(_mockdata));

    DrawUtil(context).close();
    update();
  }

  archiveDel(index) async {
    chatArchive.removeAt(index);
    await saveArchive();
    update();
  }

  Future<void> saveArchive() async {
    await OiStorage.set(StoreageKey.ARCHIVE_LIST, jsonEncode(chatArchive));
  }

  @override
  void onClose() {
    super.onClose();
    _mockdata = [];
    oifocusNode.dispose();
    userTalkTextController.dispose();
    scrollController.dispose();
    submitWorker.dispose();
  }

  reSendQuestion(int? itemIndex) {
    if (itemIndex != 0) {
      ChatMessage userQuestion = _mockdata[itemIndex! - 1];
      userTalkTextController.text = userQuestion.content;
      onSubmit();
    }
  }
}
